package com.jinzecloud.fiction.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jinzecloud.fiction.bean.TbAdmin;
import com.jinzecloud.fiction.execption.Code;
import com.jinzecloud.fiction.utils.R;
import com.jinzecloud.fiction.utils.RedisUtils;
import com.jinzecloud.fiction.vo.TbAdminVo;
import com.jinzecloud.fiction.vo.TbAdminVos;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HandlerInterceptorAdapter implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${fiction.admin.token}")
    String tokenPrefix;
    public HandlerInterceptorAdapter(RedisUtils redisUtils,String tokenPrefix) {
        this.redisUtils = redisUtils;
        this.tokenPrefix = tokenPrefix;
    }

    /**
     * 目标方法执行前
     * 该方法在控制器处理请求方法前执行，其返回值表示是否中断后续操作
     * 返回 true 表示继续向下执行，返回 false 表示中断后续操作
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        TbAdminVo tbAdmin = (TbAdminVo) redisUtils.get(tokenPrefix + authorization);
        if (tbAdmin != null){
            return true;
        }else {
            response.setContentType("application/json:charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            Map map = new HashMap();
            map.put("code",Code.TOKENPASTDUE_EXCEPTION.getCode());
            map.put("msg",Code.TOKENPASTDUE_EXCEPTION.getMsg());
            String jsonString = JSONObject.toJSONString(map);
            response.getWriter().append(jsonString);
            return false;
        }
    }
    /**
     * 目标方法执行后
     * 该方法在控制器处理请求方法调用之后、解析视图之前执行
     * 可以通过此方法对请求域中的模型和视图做进一步修改
     */
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//    }
//    /**
//     * 页面渲染后
//     * 该方法在视图渲染结束后执行
//     * 可以通过此方法实现资源清理、记录日志信息等工作
//     */
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//    }
}

